// cloudfunctions/sendMessage/index.js
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const {
            fromUserId,
            toUserId,
            content,
            contentType = 'text',
            goodsId
        } = event

        // 参数验证
        if (!fromUserId || !toUserId || !content || !goodsId) {
            return {
                success: false,
                message: '参数缺失: fromUserId, toUserId, content, goodsId 是必需参数'
            }
        }

        // 生成会话ID: buyerId_sellerId_goodsId
        const conversationId = fromUserId < toUserId ?
            `${fromUserId}_${toUserId}_${goodsId}` :
            `${toUserId}_${fromUserId}_${goodsId}`

        // 1. 保存消息
        const messageResult = await db.collection('messages').add({
            data: {
                fromUserId,
                toUserId,
                content,
                contentType,
                createTime: db.serverDate(),
                isRead: false,
                goodsId,
                messageId: `MSG_${Date.now()}`
            }
        })

        const messageId = messageResult._id
        console.log('消息ID:', messageId, '会话ID:', conversationId);

        // 2. 更新或创建会话
        const now = db.serverDate()

        // 查询会话
        const conversationQuery = await db.collection('conversations')
            .where({
                conversationId
            })
            .limit(1)
            .get();

        const conversationExists = conversationQuery.data.length > 0;
        const conversationDoc = conversationExists ? conversationQuery.data[0] : null;

        let conversationResult;
        if (conversationExists) {
            // 会话已存在，更新
            conversationResult = await db.collection('conversations')
                .doc(conversationDoc._id)
                .update({
                    data: {
                        latestMessage: messageId,
                        updateTime: now,
                        unreadCount: fromUserId === toUserId ? 0 : _.inc(1)
                    }
                });
        } else {
            // 会话不存在，创建
            conversationResult = await db.collection('conversations')
                .add({
                    data: {
                        conversationId,
                        buyerId: fromUserId < toUserId ? fromUserId : toUserId,
                        sellerId: fromUserId < toUserId ? toUserId : fromUserId,
                        goodsId,
                        latestMessage: messageId,
                        updateTime: now,
                        unreadCount: fromUserId === toUserId ? 0 : 1,
                        createTime: now,
                        isDeleted: {
                            [fromUserId]: false,
                            [toUserId]: false
                        }
                    }
                });
        }
        console.log('会话操作结果:', conversationResult);

        // 3. 更新用户消息状态
        await Promise.all([
            updateUserMessageStatus(fromUserId, conversationId, messageId, now, false),
            updateUserMessageStatus(toUserId, conversationId, messageId, now, true)
        ])

        return {
            success: true,
            message: '消息发送成功',
            messageId
        }

    } catch (error) {
        console.error('发送消息失败:', error)
        return {
            success: false,
            message: error.message || '发送消息失败'
        }
    }
}

// 更新用户消息状态
async function updateUserMessageStatus(userId, conversationId, messageId, now, isReceiver) {
    const statusQuery = await db.collection('user_message_status')
        .where({
            userId,
            conversationId
        })
        .limit(1)
        .get();

    const statusExists = statusQuery.data.length > 0;
    const statusDoc = statusExists ? statusQuery.data[0] : null;

    if (statusExists) {
        return db.collection('user_message_status')
            .doc(statusDoc._id)
            .update({
                data: {
                    latestMessage: messageId,
                    updateTime: now,
                    unreadCount: isReceiver ? _.inc(1) : 0
                }
            });
    } else {
        return db.collection('user_message_status')
            .add({
                data: {
                    userId,
                    conversationId,
                    latestMessage: messageId,
                    updateTime: now,
                    createTime: now,
                    unreadCount: isReceiver ? 1 : 0
                }
            });
    }
}